package com.foolishbird.sdk.ui.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.foolishbird.sdk.ui.model.ActivityPageInfo;
import com.foolishbird.sdk.ui.model.PromotionInfo;
import com.foolishbird.sdk.utils.WL;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

public class ActivityCenterActivity extends AppBaseActivity {

    private static final String TAG = ActivityCenterActivity.class.getSimpleName();
    private static final String ACTIVITY_CENTER_DATA = "ActivityPageInfo";

    private TextView mActivityCenterTitle;
    private WebView mActivityCenterBrowserView;
    private ProgressBar mActivityCenterLoadingBar;

    private ActivityPageInfo mActivityPageInfo;
    private int mCurrentLoadingPagePosition;
    private long mCurrentDownloadingTaskId;

    public static void forwardActivityCenterActivity(Context context, ActivityPageInfo info) {
        Intent intent = new Intent(context, ActivityCenterActivity.class);
        intent.putExtra(ACTIVITY_CENTER_DATA, info);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutIdentifier("hnssn_activity_activity_center"));

        mActivityPageInfo = getIntent().getParcelableExtra(ACTIVITY_CENTER_DATA);

        mActivityCenterTitle = findViewById(getViewIdentifier("hnssn_activity_center_title"));
        mActivityCenterBrowserView = findViewById(getViewIdentifier("hnssn_activity_center_browser"));
        mActivityCenterLoadingBar = findViewById(getViewIdentifier("hnssn_activity_center_progressbar"));

        WebSettings webSettings = mActivityCenterBrowserView.getSettings();
        webSettings.setUseWideViewPort(true);
        webSettings.setSupportZoom(true);
        webSettings.setAppCacheEnabled(false);
        webSettings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        webSettings.setDomStorageEnabled(true);
        webSettings.setJavaScriptEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            webSettings.setMediaPlaybackRequiresUserGesture(false);
        }
        mActivityCenterBrowserView.setWebChromeClient(new ActivityWebChromeClient());
        mActivityCenterBrowserView.addJavascriptInterface(new DownloadJavaScriptInterface(), "activity");

        mCurrentLoadingPagePosition = mActivityPageInfo != null ? mActivityPageInfo.getCurrentUrlIndex() : 0;
        String url = mActivityPageInfo != null ? mActivityPageInfo.getCurrentPageUrl() : "https://www.7749g.com";
        loadActivityCenterContent(url);
    }

    private void loadActivityCenterContent(String url) {
        if (!TextUtils.isEmpty(url)) {
            mActivityCenterBrowserView.loadUrl(url);
        }
    }

    public void onBrowserHistoryBackClick(View view) {
        if (mCurrentLoadingPagePosition > 0 && mActivityPageInfo != null) {
            mCurrentLoadingPagePosition--;
            loadActivityCenterContent(mActivityPageInfo.getPageUrl(mCurrentLoadingPagePosition));
        }
    }

    public void onBrowserHistoryForwardClick(View view) {
        if (mActivityPageInfo != null && mCurrentLoadingPagePosition < mActivityPageInfo.urlSize() - 1) {
            mCurrentLoadingPagePosition++;
            loadActivityCenterContent(mActivityPageInfo.getPageUrl(mCurrentLoadingPagePosition));
        }
    }

    public void onBrowserHistoryRefreshClick(View view) {
        if (mActivityPageInfo != null) {
            loadActivityCenterContent(mActivityPageInfo.getPageUrl(mCurrentLoadingPagePosition));
        }
    }

    public void onBrowserHistoryExitClick(View view) {
        finish();
    }

    private void startPromotionApkDownloadTask(PromotionInfo promotionInfo) {
//        if(mCurrentDownloadingTaskId > 0){
//            ActivitiesDownloader downloader = ActivitiesDownloader.getImpl();
//            if(downloader.isDownloading(mCurrentDownloadingTaskId)){
//                String message = getString(getStringIdentifier("hnssn_version_update_downloading"));
//                Toast.makeText(this, message, Toast.LENGTH_LONG).show();
//                return;
//            }
//        }
//
//        final String downloadUrl = promotionInfo != null ? promotionInfo.getPromotionUrl() : "";
//        final String title = promotionInfo != null ? promotionInfo.getAppName() : "";
//        final String description = promotionInfo != null ? promotionInfo.getAppDescription() : "";
//        runOnUiThread(new Runnable() {
//            @Override
//            public void run() {
//                if (!TextUtils.isEmpty(downloadUrl)) {
//                    ActivitiesDownloader downloader = ActivitiesDownloader.getImpl();
//                    String extension = String.valueOf(Math.abs(downloadUrl.hashCode()));
//                    File storageFile = downloader.randomMakeDownloadStorageFile(extension);
//                    mCurrentDownloadingTaskId = downloader.startVersionDownloadTask(downloadUrl, storageFile, title, description, true);
//                }
//            }
//        });
    }

    private class ActivityWebChromeClient extends WebChromeClient {

        @Override
        public void onReceivedTitle(WebView view, String title) {

            super.onReceivedTitle(view, title);
            if (!TextUtils.isEmpty(title)) {
                mActivityCenterTitle.setText(title);
            } else {
                mActivityCenterTitle.setText(getStringIdentifier("app_name"));
            }
        }

        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (mActivityCenterLoadingBar != null) {
                if (newProgress == 100) {
                    mActivityCenterLoadingBar.setVisibility(View.GONE);
                } else {
                    if (View.VISIBLE != mActivityCenterLoadingBar.getVisibility()) {
                        mActivityCenterLoadingBar.setVisibility(View.VISIBLE);
                    }
                    mActivityCenterLoadingBar.setProgress(newProgress);
                }
            }
            super.onProgressChanged(view, newProgress);
        }
    }

    private class DownloadJavaScriptInterface {

        /**
         * {"promotion_url":"www.xxxx.com"}
         *
         * @param json
         */
        @JavascriptInterface
        public void callDownloadDownUrl(String json) {
            WL.d(TAG, "callDownloadDownUrl =======>json: " + json);
            JsonParser jsonParser = new JsonParser();
            JsonElement jsonElement = jsonParser.parse(json);
            if (jsonElement.isJsonObject()) {
                JsonObject jsonObject = jsonElement.getAsJsonObject();
                startPromotionApkDownloadTask(new Gson().fromJson(jsonObject, PromotionInfo.class));
            }
        }
    }

}
